import { Card, Table } from 'antd'
import { reqDictLists } from '@api/datadictionary/datamanagement'
import { useEffect, useState } from 'react'
import { Idataitem, IdataType } from '@api/datadictionary/model'
import { RightOutlined, DownOutlined } from '@ant-design/icons'

export default function Datadictionary() {
  //设置Table加载效果
  const [loading, setLoading] = useState(false)
  //存储Table渲染数据
  const [data, setData] = useState<IdataType>([])
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '编码',
      dataIndex: 'dictCode',
      key: 'dictCode',
    },
    {
      title: '值',
      dataIndex: 'value',
      key: 'value',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
  ]

  //获取数据函数
  async function getDataList(value: number = 1) {
    setLoading(true)
    const result = await reqDictLists(value)
    setLoading(false)
    return result
  }

  //挂载阶段渲染一级数据
  useEffect(() => {
    async function fetchData() {
      const result = await getDataList()
      //让一级数据有可展开图标
      setData(
        result.map((item) => {
          return {
            ...item,
            children: [],
            isLeaf: true,
          }
        })
      )
    }
    fetchData()
  }, [])

  //表格点击展开下一级数据按钮时触发函数
  const handleExpand = (onExpand: any, record: any) => {
    return async (e: any) => {
      const data = await getDataList(record.id)
      record.children = data.map((item: any) => {
        return {
          ...item,
          isLeaf: false,
        }
      })
      onExpand(record, e)
    }
  }

  return (
    <Card>
      <Table
        loading={loading}
        rowKey="id"
        bordered
        columns={columns}
        dataSource={data}
        pagination={false}
        expandable={{
          expandIcon: ({ expanded, onExpand, record }) => {
            if (!record.hasChildren) {
              return (
                <span className="dict-box" style={{ marginRight: 23}}></span>
              )
            }
            return expanded ? (
              <DownOutlined
                onClick={(e) => onExpand(record, e)}
                style={{ color: '#999', marginRight: 10, width: 12 }}
              />
            ) : (
              <RightOutlined
                onClick={handleExpand(onExpand, record)}
                style={{ color: '#999', marginRight: 10, width: 12 }}
              />
            )
          },
        }}
      ></Table>
    </Card>
  )
}
